﻿using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using System;

namespace BeiraBaga
{
    public partial class Timesheet : UserControl
    {
        #region Members

        private Controller _controller;
        private DateTime _start, _end;

        #endregion

        #region Properties

        public Controller Controller { set { _controller = value; } }

        public GridView GridView { get { return gridView; } }

        public DateTime Start { set { _start = value.Date; } }

        public DateTime End { set { _end = value.Date; } }

        #endregion

        public Timesheet()
        {
            InitializeComponent();
        }

        #region Protected Overrides

        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);
            if (_controller == null)
                return;
            employeesViewBindingSource.DataSource = _controller.Employees;
        }

        public void Reload()
        {
            tDU_HorariosBindingSource.DataSource = null;
            tDU_HorariosBindingSource.DataSource = _controller.GetTimesheet(_start, _end);
        }

        #endregion

        #region Event Handlers

        private void gridView_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            var timesheet = (TDU_Horarios)e.Row;
            tDU_HorariosBindingSource.EndEdit();
            //_controller.Save(timesheet);
        }

        private void employeeRepositoryItemLookUpEdit_EditValueChanged(object sender, System.EventArgs e)
        {
            var index = ((LookUpEdit)sender).ItemIndex;
            var employee = (string)employeeRepositoryItemLookUpEdit.GetDataSourceValue("Fornecedor", index);
            var name = (string)employeeRepositoryItemLookUpEdit.GetDataSourceValue("Nome", index);
            var timesheet = ((TDU_Horarios)gridView.GetRow(gridView.FocusedRowHandle));
            timesheet.CDU_Funcionario = employee;
            timesheet.CDU_Nome = name;
        }

        private void tDU_HorariosBindingSource_CurrentItemChanged(object sender, System.EventArgs e)
        {
            _controller.Save();
        }

        #endregion        
    }
}
